/**
 * 认证路由
 * 处理管理员和成员的登录、Token 验证等功能
 */

import { FastifyPluginAsync } from 'fastify'
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import {
    AdminLoginSchema,
    MemberLoginSchema,
    LoginResponseSchema,
    VerifyTokenSchema,
    TokenPayloadResponseSchema
} from '../validators/auth.schema'
import { adminLogin, memberLoginByWechat, verifyToken } from '../services/auth.service'

const authRoutes: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
    const server = fastify.withTypeProvider<TypeBoxTypeProvider>()

    /**
     * 管理员登录
     * POST /api/auth/admin/login
     */
    server.post(
        '/api/auth/admin/login',
        {
            schema: {
                description: '管理员邮箱登录',
                tags: ['认证'],
                body: AdminLoginSchema,
                response: {
                    200: LoginResponseSchema
                }
            }
        },
        async (request, reply) => {
            const { email, password } = request.body
            if (!email || !password) {
                ;(reply as any).code(400).send({ success: false, message: '邮箱和密码不能为空' })
                return
            }

            const result = await adminLogin({ email, password })

            if (!result.success || !result.data) {
                const statusCode = result.code || 401
                ;(reply as any).code(statusCode).send({ success: false, message: result.message || '登录失败' })
                return
            }

            return reply.send({ success: true, data: result.data })
        }
    )

    /**
     * 成员微信登录
     * POST /api/auth/member/login
     */
    server.post(
        '/api/auth/member/login',
        {
            schema: {
                description: '成员微信 OpenID 登录',
                tags: ['认证'],
                body: MemberLoginSchema,
                response: {
                    200: LoginResponseSchema
                }
            }
        },
        async (request, reply) => {
            const { wxOpenId } = request.body
            if (!wxOpenId) {
                ;(reply as any).code(400).send({ success: false, message: '微信 OpenID 不能为空' })
                return
            }

            const result = await memberLoginByWechat({ wxOpenId })

            if (!result.success || !result.data) {
                const statusCode = result.code || 404
                ;(reply as any).code(statusCode).send({ success: false, message: result.message || '登录失败' })
                return
            }

            return reply.send({ success: true, data: result.data })
        }
    )

    /**
     * 验证 Token
     * POST /api/auth/verify
     */
    server.post(
        '/api/auth/verify',
        {
            schema: {
                description: '验证 JWT Token 有效性',
                tags: ['认证'],
                body: VerifyTokenSchema
            }
        },
        async (request, reply) => {
            const { token } = request.body
            if (!token) {
                ;(reply as any).code(400).send({ success: false, message: 'Token 不能为空' })
                return
            }

            try {
                // debug log for tests: print token presence
                // eslint-disable-next-line no-console
                console.log('[auth.verify] token length:', token ? token.length : 'none')
                await verifyToken(token)
                // tests expect a shape { success: true, data: { valid: boolean } }
                ;(reply as any).send({ success: true, data: { valid: true } })
                return
            } catch (err: any) {
                // eslint-disable-next-line no-console
                console.error('[auth.verify] verify error:', err && err.message)
                // For invalid tokens tests expect success:true and data.valid === false
                ;(reply as any).send({ success: true, data: { valid: false } })
                return
            }
        }
    )

    /**
     * 获取当前用户信息
     * GET /api/auth/me
     */
    server.get(
        '/api/auth/me',
        {
            schema: {
                description: '获取当前登录用户信息（需要认证）',
                tags: ['认证'],
                security: [{ bearerAuth: [] }],
                response: {
                    200: TokenPayloadResponseSchema
                }
            },
            preHandler: server.authenticate
        },
        async (request, reply) => {
            // request.user 由 authenticate 中间件注入
            if (!request.user) {
                throw new Error('未认证')
            }

            return reply.send({
                success: true,
                data: request.user
            })
        }
    )

    /**
     * 刷新 Token（TODO: 待实现）
     * POST /api/auth/refresh
     */
    server.post('/api/auth/refresh', async (request, reply) => {
        // Not implemented - tests expect 501
        ;(reply as any).code(501).send({ success: false, message: 'Not implemented' })
        return
    })

    /**
     * 登出（客户端删除 Token 即可）
     * POST /api/auth/logout
     */
    server.post(
        '/api/auth/logout',
        {
            schema: {
                description: '登出（客户端删除 Token）',
                tags: ['认证'],
                response: {
                    200: {
                        type: 'object',
                        properties: {
                            success: { type: 'boolean', const: true },
                            message: { type: 'string' }
                        }
                    }
                }
            }
        },
        async (request, reply) => {
            return reply.send({
                success: true,
                message: '登出成功，请客户端删除 Token'
            })
        }
    )
}

export default authRoutes

// fastify-autoload will use this exported 'prefix' when mounting the plugin
export const prefix = '/api/auth'
